package com.practice.rpc.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class RpcTcpTransport {
	private String host;
	private int port;
	public RpcTcpTransport(String host, int port) {
		super();
		this.host = host;
		this.port = port;
	}
	
	public Object send(RpcRequest request) {
		Socket socket = null;
		ObjectOutputStream out = null;
		ObjectInputStream in = null;
		try {
			socket = new Socket(host, port);
			out = new ObjectOutputStream(socket.getOutputStream());
			out.writeObject(request);
			out.flush();
			
			in = new ObjectInputStream(socket.getInputStream());
			return in.readObject();
		} catch (Exception e) {
			throw new RuntimeException("发起远程调用异常：", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
